package com.hk.yajin.function.videos.activity;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;

import com.hk.developmentlib.baseben.NewWorkBean;
import com.hk.developmentlib.callback.HttpCallBack;
import com.hk.developmentlib.utills.FastjsonUtils;
import com.hk.developmentlib.utills.NetworkInfoUtils;
import com.hk.developmentlib.utills.UiUtil;
import com.hk.yajin.R;
import com.hk.yajin.base.BaseActivity;
import com.hk.yajin.function.members.activity.LoginAndRegisterActivity;
import com.hk.yajin.function.members.activity.RechargeGlodActivity;
import com.hk.yajin.manager.UserInfoManager;
import com.hk.yajin.model.Video;
import com.hk.yajin.utills.HttpRequestUtils;
import com.hk.yajin.utills.url.UrlConstants;
import com.hk.yajin.view.MyVideoView;
import com.hk.yajin.view.PopupWindows;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VideoDetailActivity extends BaseActivity implements MyVideoView.OnHandleVideoView {

    @BindView(R.id.vv_play)
    MyVideoView vvPlay;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.tv_sum)
    TextView tvSum;
    @BindView(R.id.tv_my_video)
    TextView tvBuy;
    @BindView(R.id.iv_switch)
    ImageView ivSwitch;

    private Video video;
    private boolean videoViewInited = false;
    private int playPosition;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        ButterKnife.bind(this);
        initView();
        initBaseData();
        judgePermession();
    }

    private void initBaseData() {
        String dataString = getIntent().getStringExtra(VIDEO);
        if (TextUtils.isEmpty(dataString)) {
            finish();
        } else {
            video = FastjsonUtils.getBeanObject(dataString, Video.class);
            tvTitle.setText(video.getV_title());
            tvSum.setText(video.getV_brief());
        }
    }


    private void initView() {
        vvPlay.getLayoutParams().height = UiUtil.getScreenWidth() * 440 / 720;
    }

    private void judgePermession() {
        initVideoDetail();
    }


    /**
     * 弹出菜单
     */
    private void showPopupWindows() {
        new PopupWindows(mContext,getString(R.string.confirm_sigle_video) ,video.getV_gold(), tvBuy, new PopupWindows.PopOnClickListener() {
            @Override
            public void onClickYes() {
                httpBuyVideo();
            }

            @Override
            public void onClickNo() {

            }
        });
    }

    private void httpBuyVideo() {
        showLoadingView();
        Map<String, Object> reqParam = UserInfoManager.getUserKeyMapIfLogin();
        reqParam.put("v_id", video.getV_id());
        HttpRequestUtils.post(false, UrlConstants.FUNCTION_BUY_VIDEO, reqParam, false, new HttpCallBack() {
            @Override
            public void onSucced(String data) {
                hideLoadingView();
                showShortToast("购买成功");
                judgePermession();
            }

            @Override
            public void onBadHttp(String tip) {
                hideLoadingView();
                showShortToast(tip);
            }

            @Override
            public void onErrorCode(NewWorkBean bean) {
                hideLoadingView();
                if (bean.getCode()==102) {
                    showShortToast("金币不足，请先充值");
                    startActivity(RechargeGlodActivity.class);
                } else {
                    showShortToast(bean.getMsg());
                }
            }
        });
    }

    private void initVideoView() {
        if (!videoViewInited) {
            MediaController mc = new MediaController(this);

            vvPlay.setMediaController(mc);
            vvPlay.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    showShortToast("视频播放出错啦！");
                    return true;
                }
            });
            vvPlay.setOnHandleVideoView(this);
            vvPlay.setVideoPath(video.getV_video());
            vvPlay.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    vvPlay.start();
                }

            });

            vvPlay.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    // finish();

                }
            });
            videoViewInited = true;
        }

    }

    @Override
    protected void onBackPressd() {
        finish();
    }

    @OnClick({R.id.iv_back, R.id.iv_play, R.id.iv_share, R.id.iv_switch})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_switch:
                switchScreen();
                break;
            case R.id.iv_back:
                onBackPressd();
                break;
            case R.id.iv_play:
                if (TextUtils.isEmpty(video.getV_video()) && !UserInfoManager.getInstance().isLogin()) {
                    showShortToast("请先登录");
                    startActivityForResult(new Intent(getApplication(), LoginAndRegisterActivity.class), RESULT_FIRST_USER);
                } else {
                    if (!TextUtils.isEmpty(video.getV_video())) {
                        hanldeNetWorkState();
                    } else {
                        tvBuy.callOnClick();
                    }
                }
                break;
            case R.id.iv_share:
                share();
                break;
        }
    }


    private void share() {
        if (video == null || TextUtils.isEmpty(video.getV_video())) {
            showShortToast("抱歉，您无分享权限");
            return;
        }
        UMVideo shareUMVideo = new UMVideo(video.getV_video());
        shareUMVideo.setTitle(video.getV_title());
        shareUMVideo.setThumb(new UMImage(this, video.getV_cover()));
        shareUMVideo.setDescription(video.getV_brief());
        new ShareAction(this).withMedia(shareUMVideo)
                .setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {

                        if (throwable != null) {
                            showShortToast(throwable.getMessage());
                        }
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {
                        showShortToast("onCancel");
                    }
                }).open();
    }

    private void hanldeNetWorkState() {
        switch (checkWifiState()) {
            case -1:
                showShortToast("请检查网络连接");
                if (videoViewInited) {
                    vvPlay.stopPlayback();
                }
                break;
            case 0:
                new AlertDialog.Builder(this).setTitle("警告")//设置对话框标题
                        .setMessage("您当前使用数据流量，是否继续播放？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                initVideoView();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
                break;
            case 1:
                if (videoViewInited) {
                    vvPlay.start();
                } else {
                    initVideoView();
                }

                break;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (vvPlay != null && videoViewInited) {
            vvPlay.seekTo(playPosition);
            vvPlay.start();
        }
    }

    @Override
    protected void onPause() {
        if (vvPlay != null && videoViewInited) {
            vvPlay.pause();
            playPosition = vvPlay.getCurrentPosition();
        }
        super.onPause();

    }

    // 获取网络类型，-1表示没网络，0表示移动数据，1表示wifi
    private int checkWifiState() {
        return new NetworkInfoUtils(this).getNetType();
    }

    @Override
    public void onPlayStart() {
        ivPlay.setVisibility(View.GONE);
    }

    @Override
    public void onPlayPause() {
        ivPlay.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPlayStopPlayback() {
        ivPlay.setVisibility(View.VISIBLE);
    }


    private void initVideoDetail() {
        showLoadingView();
        Map<String, Object> reqParam = UserInfoManager.getUserKeyMapIfLogin();
        reqParam.put("id", String.valueOf(video.getV_id()));
        HttpRequestUtils.post(true, UrlConstants.FUNCTION_VIDEO_DETAIL, reqParam, false, new HttpCallBack() {
            @Override
            public void onSucced(String data) {
                hideLoadingView();
                video = FastjsonUtils.getBeanObject(data, Video.class);
                tvTitle.setText(video.getV_title());
                tvSum.setText(video.getV_brief());
                tvBuy.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onBadHttp(String tip) {
                hideLoadingView();
                showShortToast("视频请求出错~看看别的视频吧");
                finish();
            }

            @Override
            public void onErrorCode(NewWorkBean bean) {
                hideLoadingView();
                switch (bean.getCode()) {
                    case 111://未登录
                        showShortToast("请先登录");
                        startActivityForResult(new Intent(getApplication(), LoginAndRegisterActivity.class), RESULT_FIRST_USER);
                        break;
                    //处理单买
                    case 112:
                    case 113:
                        video = FastjsonUtils.getBeanObject(bean.getData(), Video.class);
                        tvTitle.setText(video.getV_title());
                        tvSum.setText(video.getV_brief());
                        tvBuy.setVisibility(View.VISIBLE);
                        tvBuy.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                showPopupWindows();
                            }
                        });
                        break;
                    case 212:
                    case 213:
                        //处理包月
                        video = FastjsonUtils.getBeanObject(bean.getData(), Video.class);
                        tvTitle.setText(video.getV_title());
                        tvSum.setText(video.getV_brief());
                        tvBuy.setVisibility(View.VISIBLE);
                        tvBuy.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(VideoDetailActivity.this, BuySeriesVideoActivity.class);
                                intent.putExtra(VIDEO, FastjsonUtils.toJSONString(video));
                                startActivityForResult(intent, RESULT_FIRST_USER);
                            }
                        });
                        break;
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        judgePermession();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_FIRST_USER && resultCode == RESULT_OK) {
            judgePermession();
        }
    }


    /*控制横竖屏*/
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        ResetVideoPlayer();
        super.onConfigurationChanged(newConfig);
    }

    private void ResetVideoPlayer() {
        // 设置显示名称
        int mCurrentOrientation = getResources().getConfiguration().orientation;
        if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            SetfullScreen(false);
            // rlt_video.setLayoutParams(new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, UiUtil.dip2px(200)));
            vvPlay.getLayoutParams().height = UiUtil.dip2px(200);
        } else if (mCurrentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            //llyInfo.setVisibility(View.GONE);
            SetfullScreen(true);
            //  rlt_video.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            vvPlay.getLayoutParams().height = UiUtil.getScreenHeight();
        }
        vvPlay.requestFocus();
    }

    /**
     * 设置是否进入全屏
     *
     * @param enable
     */
    public void SetfullScreen(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            hideVirtualButtons();
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    /**
     * 隐藏虚拟导航键，使用于api 19+
     */
    @TargetApi(11)
    private void hideVirtualButtons() {
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_IMMERSIVE);
        }
    }


    private void switchScreen() {
        //播放器右下角的全屏或退出全屏按钮
        if (this.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (vvPlay != null && vvPlay.isPlaying()) {
            new AlertDialog.Builder(VideoDetailActivity.this).setTitle(R.string.tip)//设置对话框标题
                    .setMessage(R.string.quittip)
                    .setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton(R.string.cancle, null)
                    .show();
        } else {
            finish();
        }
    }
}
